package com.example.jvmsource.resourcesload;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.WritableResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.context.support.ServletContextResource;

/**
 * @author zhouyu
 * @Description:使用spring框架下的reource加载各种资源文件
 */
public class SpringReourceLoad {
  WritableResource resource;

  /**
   * 获取系统指定文件路径的文件
   */
  public void getSysFile() {
    String filePath = "";
    resource = new FileSystemResource(filePath);
  }

  /**
   * 获取classPath下的文件
   */
  public void getClasspathFile() {
    ClassPathResource classPathResource = new ClassPathResource("application.yml");
  }

  /**
   * 获取web应用根目录下的资源
   */
  public void getServerLetResource( HttpServletRequest request) {
    ServletContextResource servletContextResource = new ServletContextResource(request.getSession().getServletContext(),"/WEB-INF/test.xml");
  }

  /**
   * 通过ResourceLoader的继承DefaultResourceLoader获取资源文件：仅仅是spring支持的资源地址前缀
   */
  public void getByDefaultClassLoader() {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    resourceLoader.getResource("");
  }

  /**
   * 通过ResourcePatternResolver获取资源：不仅适用spring支持的资源地址前缀，ant风格的资源地址也适用 PathMatchingResourcePatternResolver是ResourcePatternResolver的标准实现
   */
  public void getByClassLoaderResolver() {
    ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
    //支持ant+spring前缀的地址
    try {
      Resource[] resources = patternResolver.getResources("classpath*:com/xgj/conf/**/*.xml");
      //classpath下的文件
      Resource[] resources1 = patternResolver.getResources("application.yml");
      //文件绝对路劲
      Resource[] resources2 = patternResolver.getResources("file:/D:/workspace/workspace-jee/HelloSpring/hello-spring4/src/main/java/com/xgj/conf/conf2/test2.xml");
      //从服务器读取
      Resource[] resources3 = patternResolver.getResources("http://127.0.0.1:8080/hello-spring4/index.jsp");
    } catch (IOException e) {
      e.printStackTrace();
    }

  }


}
